<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>long-polling-demo</title>
		<script src="/js/jquery.min.js"></script>
		<link href="/css/bootstrap.min.css" rel="stylesheet">
		<style type="text/css">
			body {
				padding: 5% 15%;
			}
			.box {
				margin: 3% auto;
				padding: 0px 3%;
			}
		</style>
	</head>
	<body>
		<input type="text" class="form-control" id="monitorInput" placeholder="" value="longPolling">
		<small id="monitorInputHelp" class="form-text text-muted">监听 dataId（monitor dataId）,默认监听: longPolling</small>

		<div class="card box">
			<div class="card-body">
				<h3>监听结果（monitor）</h3>
			</div>
			<div class="console"></div>
		</div>
		
		<script type="text/javascript">
			function getFormatDate() {
				var date = new Date();
				var month = date.getMonth() + 1;
				var strDate = date.getDate();
				if (month >= 1 && month <= 9) {
					month = "0" + month;
				}
				if (strDate >= 0 && strDate <= 9) {
					strDate = "0" + strDate;
				}
				var currentDate = date.getFullYear() + "-" + month + "-" + strDate
						+ " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
				return currentDate;
			}
			
			function longPolling() {
			  $.ajax({
			  	url: 'http://localhost:8080/longPolling',
				type: "GET",
				data:{
					dataId: $("#monitorInput").val()
				},
			  	// timeout: 30000,
			  	success: function(data) {
					if (data != null) {
						$(".console").append('<div class="alert alert-primary" role="alert">' + getFormatDate() + ', ' + data + '</div>');
					} else {
						$(".console").append('<div class="alert alert-secondary" role="alert">' + getFormatDate() + ', 超时后数据没有发生变化</div>');
					}
					longPolling();
			  	}, error: function(xhr,textStatus) {
			  		//console.log('error:'+textStatus);
					$(".console").append('<div class="alert alert-danger" role="alert">'+getFormatDate() + ", " + textStatus+'</div>');
					longPolling();
			  	}
			  });
			}
			longPolling();
		</script>
	</body>
</html>
